import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:news_f/news.dart';
import 'package:flutter/services.dart' show rootBundle;

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<News> newsList = [];
  @override
  void initState() {
    super.initState();
    readJSON('assets/data/news.json');
  }

  readJSON(assetsPath) async {
    String json = await rootBundle.loadString(assetsPath);
    List<dynamic> tmpJSONList = jsonDecode(json);
    tmpJSONList.forEach((element) => newsList.add(News.fromJson(element)));
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
        itemBuilder: (context, index) {
          News news = newsList[index];
          return ListTile(
            onTap: () => Navigator.of(context)
                .pushNamed('/detail', arguments: {"item": news}),
            leading: Image.network(
              news.img ?? "",
              width: 80,
              height: 80,
              fit: BoxFit.cover,
            ),
            title: Text(
              news.title ?? "",
              maxLines: 2,
              style: TextStyle(fontSize: 12),
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: Text(news.desc ?? "",
                maxLines: 2,
                style: TextStyle(fontSize: 10),
                overflow: TextOverflow.ellipsis),
          );
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 1,
            color: Colors.black,
          );
        },
        itemCount: newsList.length);
  }
}
